var fs = require('fs');
var path = require('path');
var default_dir_mode = 666;

//-判断文件是否存在-
function isFileExist(filename)
{
	var bExist = path.existsSync(filename);
	return bExist;
}

//-创建目录-
function createDir(rootpath, subpath)
{
	var dirs = subpath.split("/");
	
	var curdir = rootpath;
	for(var i=0; i<dirs.length; i++)
	{
		if(dirs[i]=="")
			continue;
		
		curdir += ("/" + dirs[i]);
		
		if(!isFileExist(curdir))
		{
			fs.mkdirSync(curdir, default_dir_mode);
		}
	}
}

//-批量创建子目录
function createSubDir(path)
{
	var dirs = path.split("/");
	if(dirs.length<=1)
		return;

	var curdir = dirs[0];
	for(var i=1; i<dirs.length; i++)
	{
		if(dirs[i]=="")
			continue;
		curdir += ("/" + dirs[i]);
		if(!isFileExist(curdir))
			fs.mkdirSync(curdir, default_dir_mode);
	}
}

//-打开文件-
function loadFile(pathname)
{
	var data = "";
	if(isFileExist(pathname))
	{
		data = fs.readFileSync(pathname, 'utf8');
	}
		
	return data;
}

//-保存文件-
function saveFile(filename,data)
{
	//console.log("saveFile -> " + filename);
	fs.writeFileSync(filename, data, 'utf8');
}

//-日期转换为字符串-
function dtToString(dt)
{
	var str =	dt.getFullYear()+"-"+dt.getMonth()+"-"+dt.getDay()+" " +
				dt.getHours() + ":" +dt.getMinutes()+":"+dt.getSeconds()+"_"+
				dt.getMilliseconds();
	return str;
}

exports.createDir = createDir;
exports.createSubDir = createSubDir;
exports.isFileExist = isFileExist;
exports.loadFile = loadFile;
exports.saveFile = saveFile;
exports.dtToString = dtToString;